# 只有CTA proj的DB含有数据插入，本项目只有读取相关函数
from time import time
import pandas as pd
from pymongo import MongoClient, ASCENDING
from Utils.DataUtil import convertFieldlistToDict
from datetime import timedelta, datetime, date
import platform
if platform.system() == 'Linux':
    datapath = '/home/u20/mydata/futures'

class MongoDBClient(object):
    # 饿汉式 单例模式
    def __new__(cls):
        if not hasattr(cls, 'instance'):
            cls.instance = super(MongoDBClient, cls).__new__(cls)
        return cls.instance
    # 代理ip Redis 连接池
    def __init__(self):
        self.mgdb = MongoClient(host='127.0.0.1', connect=False, maxPoolSize=2000)

    def getMongoClient(self):
        return self.mgdb


# mc = MongoClient(host='192.168.50.188', port=27017)  # Mongo连接
myMongo = MongoDBClient().getMongoClient()
dbSecurities = myMongo['jq_futures']


# format=1,datetime作为index; format=2,datetime作为首列
def getFutureMinPrice(start_date, end_date, dbsec, format=2, fields=None):
    cl = dbSecurities[dbsec]
    dateend = 'T00:00:00.000Z'
    print('开始读取期货的价格信息')
    st = datetime.strptime(start_date + dateend, '%Y-%m-%dT%H:%M:%S.000Z')
    et = datetime.strptime(end_date + dateend, '%Y-%m-%dT%H:%M:%S.000Z')
    start = time()

    if fields is None:
        cursor = cl.find({"datetime": {"$lte": et, "$gte": st}})
            # .sort([("datetime", -1)])
    else:
        cursor = cl.find({"datetime": {"$lte": et, "$gte": st}}, convertFieldlistToDict(fields))
            # .sort([("datetime", -1)])

    l = list(cursor)
    df = pd.DataFrame(l)

    if df.empty:
        print('股票估值数据读取失败，程序中止')
        return

    df = df.drop_duplicates()
    df = df.drop('_id', axis=1)
    if format==1:
        df.set_index(['datetime'], inplace=True)

    end = time()
    cost = (end - start)
    print(u'数据加载完成，耗时%s秒，获得%s行数据' % (cost, df.shape[0]))

    return df


def getFutureDailyPrice(start_date, end_date, dbsec, fields=None):
    cl = dbSecurities[dbsec]
    dateend = 'T00:00:00.000Z'
    print('开始读取期货的价格信息')
    st = datetime.strptime(start_date + dateend, '%Y-%m-%dT%H:%M:%S.000Z')
    et = datetime.strptime(end_date + dateend, '%Y-%m-%dT%H:%M:%S.000Z')
    start = time()

    if fields is None:
        cursor = cl.find({"time": {"$lte": et, "$gte": st}})
            # .sort([("datetime", -1)])
    else:
        cursor = cl.find({"time": {"$lte": et, "$gte": st}}, convertFieldlistToDict(fields))
            # .sort([("datetime", -1)])

    l = list(cursor)
    df = pd.DataFrame(l)

    if df.empty:
        print('股票估值数据读取失败，程序中止')
        return

    df = df.drop_duplicates()
    df.set_index(['time'], inplace=True)
    df = df.drop('_id', axis=1)

    end = time()
    cost = (end - start)
    print(u'数据加载完成，耗时%s秒，获得%s行数据' % (cost, df.shape[0]))

    return df


def getTickData(start_date, end_date, fields=None):
    cl = dbSecurities['T_tick']
    dateend = '00:00:00.000Z'
    print('开始读取tick数据')
    st = datetime.strptime(start_date + dateend, '%Y%m%dT%H%M%S.000Z')
    et = datetime.strptime(end_date + dateend, '%Y%m%dT%H%M%S.000Z')
    start = time()

    if fields is None:
        cursor = cl.find({"datetime": {"$lte": et, "$gte": st}})
            # .sort([("datetime", -1)])
    else:
        cursor = cl.find({"datetime": {"$lte": et, "$gte": st}}, convertFieldlistToDict(fields))
            # .sort([("datetime", -1)])

    l = list(cursor)
    df = pd.DataFrame(l)

    if df.empty:
        print('tick数据读取失败，程序中止')
        return

    df = df.drop_duplicates()

    end = time()
    cost = (end - start)
    print(u'数据加载完成，耗时%s秒，获得%s行数据' % (cost, df.shape[0]))

    return df


if __name__ == '__main__':
    df = getFutureMinPrice('2021-01-01', '2021-08-31', 'T9999_Min', format=1)
    # df = getFutureDailyPrice('2021-08-23', '2021-08-31', 'T9999_Daily')
    print(df)
    # getTickData()
